<?php
/**
 * Created by PhpStorm.
 * User: mars
 * Date: 2018/8/27
 * Time: 下午11:19
 */

namespace common\helpers;


use yii\filters\auth\AuthMethod;
use yii\web\IdentityInterface;
use yii\web\Request;
use yii\web\Response;
use yii\web\UnauthorizedHttpException;
use yii\web\User;

class HttpHeaderAuth extends AuthMethod {

	public $tokenParam = 'access-token';

	/**
	 * Authenticates the current user.
	 *
	 * @param User $user
	 * @param Request $request
	 * @param Response $response
	 *
	 * @return IdentityInterface the authenticated user identity. If authentication information is not provided, null will be returned.
	 * @throws UnauthorizedHttpException if authentication information is provided but is invalid.
	 */
	public function authenticate( $user, $request, $response ) {
		$accessToken = \Yii::$app->getRequest()->getHeaders()->get($this->tokenParam);
		if (is_string($accessToken)) {
			$identity = $user->loginByAccessToken($accessToken, get_class($this));
			if ($identity !== null) {
				return $identity;
			}
		}
		if ($accessToken !== null) {
			$this->handleFailure($response);
		}

		return null;

	}


}